<script setup lang="ts">
import type { FormInstance } from 'ant-design-vue';

import { computed, ref, watch } from 'vue';

import { DictEnum } from '@vben/constants';

import { message } from 'ant-design-vue';

import { customerTransferApi } from '#/api/hm/customer/transfer';
import { renderDict } from '#/utils/render';

// Props
interface Props {
  visible: boolean;
  customerInfo?: any;
  fromStaff?: any;
  activeStaffList: any[];
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
});

// Emits
const emit = defineEmits<{
  success: [];
  'update:visible': [value: boolean];
}>();

// 响应式数据
const formRef = ref<FormInstance>();
const formData = ref({
  toStaffId: undefined,
  transferReason: '',
  remark: '',
});

const modalVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const staffOptions = computed(() =>
  props.activeStaffList
    .filter((staff) => staff.userId !== props.fromStaff?.staffId) // 排除原负责员工
    .map((staff) => ({
      label: `${staff.nickName} (${staff.deptName || '未知部门'})`,
      value: staff.userId,
    })),
);

const rules = {
  toStaffId: [{ required: true, message: '请选择新负责员工' }],
  transferReason: [
    { required: true, message: '请输入迁移原因' },
    { min: 5, message: '迁移原因至少5个字符' },
  ],
};

// 方法
const filterStaffOption = (input: string, option: any) => {
  return option.label.toLowerCase().includes(input.toLowerCase());
};

const handleSubmit = async () => {
  try {
    await formRef.value?.validate();

    const transferData = {
      customerIds: [props.customerInfo.customerId],
      toStaffId: formData.value.toStaffId,
      transferReason: formData.value.transferReason,
      remark: formData.value.remark,
      oldStaffName: props.fromStaff?.nickName,
    };
    console.log(transferData);
    await customerTransferApi.batchTransferCustomers(transferData);
    message.success('客户迁移成功');
    emit('success');
    handleCancel();
  } catch (error) {
    console.error('迁移失败:', error);
    message.error('迁移失败，请重试');
  }
};

const handleCancel = () => {
  formRef.value?.resetFields();
  formData.value = {
    toStaffId: undefined,
    transferReason: '',
    remark: '',
  };
  modalVisible.value = false;
};

// 监听弹窗显示状态，重置表单
watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      // 弹窗显示时重置表单
      formRef.value?.resetFields();
    }
  },
);
</script>

<template>
  <a-modal
    v-model:visible="modalVisible"
    title="单个客户迁移"
    width="600px"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <!-- 客户信息展示 -->
      <a-card title="客户信息" size="small" class="mb-4">
        <a-descriptions :column="2" size="small">
          <a-descriptions-item label="客户姓名">
            {{ customerInfo?.customerName }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ customerInfo?.phone }}
          </a-descriptions-item>
          <a-descriptions-item label="会员等级">
            <component
              :is="
                renderDict(customerInfo?.memberLevel, DictEnum.SYS_MEMBER_LEVEL)
              "
            />
          </a-descriptions-item>
          <a-descriptions-item label="客户类型">
            <component
              :is="
                renderDict(
                  customerInfo?.customerType,
                  DictEnum.SYS_CUSTOMER_TYPE,
                )
              "
            />
          </a-descriptions-item>
          <a-descriptions-item label="当前负责员工">
            {{ fromStaff?.nickName }}
          </a-descriptions-item>
          <!-- <a-descriptions-item label="最后维护时间">
            {{ customerInfo?.lastMaintainDate }}
          </a-descriptions-item> -->
        </a-descriptions>
      </a-card>

      <!-- 迁移信息 -->
      <a-form-item label="选择新负责员工" name="toStaffId">
        <a-select
          v-model:value="formData.toStaffId"
          placeholder="请选择新负责员工"
          :options="staffOptions"
          show-search
          :filter-option="filterStaffOption"
        />
      </a-form-item>

      <a-form-item label="迁移原因" name="transferReason">
        <a-textarea
          v-model:value="formData.transferReason"
          placeholder="请输入迁移原因"
          :rows="4"
          :maxlength="500"
          show-count
        />
      </a-form-item>

      <a-form-item label="备注信息" name="remark">
        <a-textarea
          v-model:value="formData.remark"
          placeholder="可输入备注信息（选填）"
          :rows="2"
          :maxlength="200"
          show-count
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style>
